package com.paishen.peiniwan.module.date;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.paishen.common.dialog.LoadingDialog;
import com.paishen.common.dialog.SelectionDialog;
import com.paishen.common.dialog.picker.PnwDateDateTimePickerDialog;
import com.paishen.common.util.BaseUtil;
import com.paishen.common.util.SpfsUtil;
import com.paishen.common.widget.TitleLayout;
import com.paishen.libamap.poisearch.PoiKeywordSearchActivity;
import com.paishen.peiniwan.App;
import com.paishen.peiniwan.BaseActivity;
import com.paishen.peiniwan.C;
import com.paishen.peiniwan.Once;
import com.paishen.peiniwan.R;
import com.paishen.peiniwan.database.User;
import com.paishen.peiniwan.frame.PnwOkCallbackAdapter;
import com.paishen.peiniwan.frame.http.PnwHttpManager;
import com.paishen.peiniwan.frame.http.response.HttpRespOrder;
import com.squareup.okhttp.Request;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class DateStartActivity extends BaseActivity {
    public static final String EXTRA_MODE_SIMPLE = "extra_mode_simple";
    public static final String EXTRA_SIMPLE_OTHER_EASE_ID = "simple_other_ease_id";
    public static final String EXTRA_SIMPLE_ORDER_ID = "simple_order_id";
    public static final String EXTRA_SIMPLE_ORDER_SUBJECT = "simple_order_subject";
    public static final String EXTRA_SIMPLE_ORDER_TIME = "simple_order_time";
    public static final String EXTRA_SIMPLE_ORDER_ADDRESS = "simple_order_address";
    private boolean isSimpleDate;
    private String simpleOtherEaseId;

    private static final int REQUEST_CODE_ADDRESS = 304;

    private View layMeal, layExercise, layMovie, layShopping, layKTV;
    private ImageView imgMeal, imgExercise, imgMovie, imgShopping, imgKTV;
    private TextView txMeal, txExercise, txMovie, txShopping, txKTV;
    private CheckBox ckGiftWanted;
    private ViewGroup layDateGift;
    private DateGiftChooseLayout layDateGiftChoose;
    private TextView txAddress, txGender, txDate;
    private SelectionDialog dlgSelectGender;
    private PnwDateDateTimePickerDialog dlgDatePicker;

    private String mSubject;
    private int mExpectGender;

    private ViewGroup layOnce;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        isSimpleDate = getIntent().getBooleanExtra(EXTRA_MODE_SIMPLE, false);
        if (isSimpleDate) {
            simpleOtherEaseId = getIntent().getStringExtra(EXTRA_SIMPLE_OTHER_EASE_ID);
            if (TextUtils.isEmpty(simpleOtherEaseId)) {
                BaseUtil.showToast(R.string.error_data);
                finish();
                return;
            }
        }

        setContentView(R.layout.activity_date_start);
        TitleLayout layTitle = (TitleLayout) findViewById(R.id.lay_title);
        layTitle.pushContent(makeBackView(), getString(R.string.date_start), null, false);

        txAddress = (TextView) findViewById(R.id.tx_address);
        txDate = (TextView) findViewById(R.id.tx_date);
        layMeal = findViewById(R.id.lay_meal);
        layExercise = findViewById(R.id.lay_exercise);
        layMovie = findViewById(R.id.lay_movie);
        layShopping = findViewById(R.id.lay_shopping);
        layKTV = findViewById(R.id.lay_ktv);
        imgMeal = (ImageView) findViewById(R.id.img_meal);
        imgExercise = (ImageView) findViewById(R.id.img_exercise);
        imgMovie = (ImageView) findViewById(R.id.img_movie);
        imgShopping = (ImageView) findViewById(R.id.img_shopping);
        imgKTV = (ImageView) findViewById(R.id.img_ktv);
        txMeal = (TextView) findViewById(R.id.tx_meal);
        txExercise = (TextView) findViewById(R.id.tx_exercise);
        txMovie = (TextView) findViewById(R.id.tx_movie);
        txShopping = (TextView) findViewById(R.id.tx_shopping);
        txKTV = (TextView) findViewById(R.id.tx_ktv);

        final View.OnClickListener onSubjectCheckedChangeListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                layMeal.setBackgroundResource(R.drawable.date_shape_start_subject_normal);
                layExercise.setBackgroundResource(R.drawable.date_shape_start_subject_normal);
                layMovie.setBackgroundResource(R.drawable.date_shape_start_subject_normal);
                layShopping.setBackgroundResource(R.drawable.date_shape_start_subject_normal);
                layKTV.setBackgroundResource(R.drawable.date_shape_start_subject_normal);
                imgMeal.setImageResource(R.mipmap.date_subject_meal_normal);
                imgExercise.setImageResource(R.mipmap.date_subject_exercise_normal);
                imgMovie.setImageResource(R.mipmap.date_subject_movie_normal);
                imgShopping.setImageResource(R.mipmap.date_subject_shopping_normal);
                imgKTV.setImageResource(R.mipmap.date_subject_ktv_normal);
                txMeal.setTextColor(0xFFFC4E52);
                txExercise.setTextColor(0xFFFC4E52);
                txMovie.setTextColor(0xFFFC4E52);
                txShopping.setTextColor(0xFFFC4E52);
                txKTV.setTextColor(0xFFFC4E52);
                switch (v.getId()) {
                    case R.id.lay_meal:
                        layMeal.setBackgroundResource(R.drawable.date_shape_start_subject_selected);
                        imgMeal.setImageResource(R.mipmap.date_subject_meal_selected);
                        txMeal.setTextColor(0xFFFFFFFF);
                        mSubject = txMeal.getText().toString();
                        break;
                    case R.id.lay_exercise:
                        layExercise.setBackgroundResource(R.drawable.date_shape_start_subject_selected);
                        imgExercise.setImageResource(R.mipmap.date_subject_exercise_selected);
                        txExercise.setTextColor(0xFFFFFFFF);
                        mSubject = txExercise.getText().toString();
                        break;
                    case R.id.lay_movie:
                        layMovie.setBackgroundResource(R.drawable.date_shape_start_subject_selected);
                        imgMovie.setImageResource(R.mipmap.date_subject_movie_selected);
                        txMovie.setTextColor(0xFFFFFFFF);
                        mSubject = txMovie.getText().toString();
                        break;
                    case R.id.lay_shopping:
                        layShopping.setBackgroundResource(R.drawable.date_shape_start_subject_selected);
                        imgShopping.setImageResource(R.mipmap.date_subject_shopping_selected);
                        txShopping.setTextColor(0xFFFFFFFF);
                        mSubject = txShopping.getText().toString();
                        break;
                    case R.id.lay_ktv:
                        layKTV.setBackgroundResource(R.drawable.date_shape_start_subject_selected);
                        imgKTV.setImageResource(R.mipmap.date_subject_ktv_selected);
                        txKTV.setTextColor(0xFFFFFFFF);
                        mSubject = txKTV.getText().toString();
                        break;
                }
            }
        };

        layMeal.setOnClickListener(onSubjectCheckedChangeListener);
        layExercise.setOnClickListener(onSubjectCheckedChangeListener);
        layMovie.setOnClickListener(onSubjectCheckedChangeListener);
        layShopping.setOnClickListener(onSubjectCheckedChangeListener);
        layKTV.setOnClickListener(onSubjectCheckedChangeListener);

        txGender = (TextView) findViewById(R.id.tx_gender);

        layDateGift = (ViewGroup) findViewById(R.id.lay_date_gift);
        layDateGiftChoose = new DateGiftChooseLayout(this);
        ckGiftWanted = (CheckBox) findViewById(R.id.ck_gift_wanted);

        if (isSimpleDate) {
            findViewById(R.id.lay_target).setVisibility(View.GONE);
            findViewById(R.id.view_devider_2).setVisibility(View.GONE);

            ckGiftWanted.setChecked(false);
            txGender.setText(R.string.date_gender_girl);
            mExpectGender = App.i().getUser().getGender() ? PnwHttpManager.Square.SQUARE_FILTER_GENDER_FEMALE : PnwHttpManager.Square.SQUARE_FILTER_GENDER_MALE;
            findViewById(R.id.lay_gift_want).setVisibility(View.GONE);
            layDateGift.addView(layDateGiftChoose);
        } else if (!App.i().getUser().getGender()) {
            txGender.setText(R.string.date_gender_boy);
            mExpectGender = PnwHttpManager.Square.SQUARE_FILTER_GENDER_MALE;

            findViewById(R.id.lay_gift_want).setVisibility(View.VISIBLE);

            ckGiftWanted.setChecked(true);
            ckGiftWanted.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    layDateGift.setVisibility(View.VISIBLE);
                    if (isChecked) {
                        layDateGift.removeView(layDateGiftChoose);
                    } else {
                        layDateGift.addView(layDateGiftChoose);
                    }
                }
            });

            layDateGift.setVisibility(View.GONE);
        } else {
            ckGiftWanted.setChecked(false);
            txGender.setText(R.string.date_gender_girl);
            mExpectGender = PnwHttpManager.Square.SQUARE_FILTER_GENDER_FEMALE;
            findViewById(R.id.lay_gift_want).setVisibility(View.GONE);
            layDateGift.addView(layDateGiftChoose);
        }

        findViewById(R.id.lay_address).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String mSearchKey = "";
                if (!TextUtils.isEmpty(mSubject)) {
                    mSearchKey = mSubject;
                }
                Intent intent = new Intent(DateStartActivity.this, PoiKeywordSearchActivity.class);
                intent.putExtra(PoiKeywordSearchActivity.EXTRA_TYPE_SEARCH, mSearchKey);
                String lat = SpfsUtil.readString(C.sp.LAT);
                String lng = SpfsUtil.readString(C.sp.LNG);
                if (!TextUtils.isEmpty(lat) && !TextUtils.isEmpty(lng)) {
                    try {
                        intent.putExtra(PoiKeywordSearchActivity.EXTRA_LAT, Double.parseDouble(lat));
                        intent.putExtra(PoiKeywordSearchActivity.EXTRA_LNG, Double.parseDouble(lng));
                    } catch (Exception e) {
                    }
                }
                startActivityForResult(intent, REQUEST_CODE_ADDRESS);
            }
        });

        findViewById(R.id.lay_date).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDataPickerDialog();
            }
        });

        findViewById(R.id.lay_target).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showSelectGenderDialog();
            }
        });

        findViewById(R.id.btn_submit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (checkOrder()) {
                    String date_from = txDate.getText().toString();
                    String address = txAddress.getText().toString();
                    String latLng = txAddress.getTag().toString();
                    double lat = Double.parseDouble(latLng.split("#")[0]);
                    double lng = Double.parseDouble(latLng.split("#")[1]);
                    long gift_id = -1;
                    if (!ckGiftWanted.isChecked()) {
                        gift_id = layDateGiftChoose.getGiftType();
                    }

                    if (isSimpleDate) {
                        requestOrderCreateSingle(mSubject, date_from, address, lat, lng, mExpectGender, gift_id);
                    } else {
                        requestOrderCreate(mSubject, date_from, address, lat, lng, mExpectGender, gift_id);
                    }
                }
            }
        });

        if (App.DEBUG_MODE) {
            txAddress.setText("夏威夷瓦胡岛檀香山(test" + System.currentTimeMillis() + ")");
            txAddress.setTag("31.2171761154#121.4639298033");
        }

        layOnce = (ViewGroup) findViewById(R.id.lay_once);
        Once.getInstance().coverDateStart(this, App.i().getUser().getGender(), layOnce);
    }


    private boolean checkOrder() {
        boolean result = true;
        if (TextUtils.isEmpty(mSubject)) {
            BaseUtil.showToast(getString(R.string.date_input_subject_choose));
            result = false;
        } else if (TextUtils.isEmpty(txDate.getText())) {
            BaseUtil.showToast(R.string.date_input_date);
            result = false;
        } else if (isDateInThePast()) {
            BaseUtil.showToast(R.string.date_time_range_error);
            result = false;
        } else if (TextUtils.isEmpty(txAddress.getText())) {
            BaseUtil.showToast(R.string.date_input_address);
            result = false;
        } else if (layDateGiftChoose.getGiftType() == DateGiftChooseLayout.TYPE_GIFT_UNSELECTED) {
            if (isSimpleDate) {
                BaseUtil.showToast(R.string.date_choose_gift);
                result = false;
            } else {
                User login = App.i().getUser();
                if (login.getGender() || (!login.getGender() && !ckGiftWanted.isChecked())) {
                    BaseUtil.showToast(R.string.date_choose_gift);
                    result = false;
                }
            }
        }
        return result;
    }

    private boolean isDateInThePast() {
        try {
            Date select = new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(txDate.getText().toString());
            if (System.currentTimeMillis() - select.getTime() > 0) {
                return true;
            }
        } catch (Exception e) {
        }
        return false;
    }

    private void showSelectGenderDialog() {
        if (dlgSelectGender == null) {
            List<SelectionDialog.Menu> menuList = new ArrayList<>();
            menuList.add(new SelectionDialog.Menu(App.i().getString(R.string.date_gender_boy), new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dlgSelectGender.dismiss();
                    txGender.setText(R.string.date_gender_boy);
                    mExpectGender = PnwHttpManager.Square.SQUARE_FILTER_GENDER_MALE;
                }
            }));
            menuList.add(new SelectionDialog.Menu(App.i().getString(R.string.date_gender_girl), new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dlgSelectGender.dismiss();
                    txGender.setText(R.string.date_gender_girl);
                    mExpectGender = PnwHttpManager.Square.SQUARE_FILTER_GENDER_FEMALE;

                }
            }));
            menuList.add(new SelectionDialog.Menu(App.i().getString(R.string.date_gender_unlimited), new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dlgSelectGender.dismiss();
                    txGender.setText(R.string.date_gender_unlimited);
                    mExpectGender = PnwHttpManager.Square.SQUARE_FILTER_GENDER_UNLIMITED;
                }
            }));
            dlgSelectGender = new SelectionDialog.Builder(DateStartActivity.this).setMenuList(menuList).create();
        }
        dlgSelectGender.show();
    }

    private void showDataPickerDialog() {
        if (dlgDatePicker == null) {
            dlgDatePicker = new PnwDateDateTimePickerDialog.Builder(DateStartActivity.this).setTitle(getString(R.string.date_input_date))
                    .setOnPnwEventDateTimeSelectedListener(new PnwDateDateTimePickerDialog.OnPnwDateDateTimeSelectedListener() {
                        @Override
                        public void onPnwDateDateTimeSelected(String dateDate) {
                            txDate.setText(dateDate);
                        }
                    }).create();
        }
        dlgDatePicker.show();
    }

    private void requestOrderCreate(String subject_type, String date_from, String address, double lat, double lng, int sex, long gift_id) {
        final LoadingDialog dlgLoading = new LoadingDialog.Builder(this).create();
        dlgLoading.show();
        PnwHttpManager.Order.create(TAG, subject_type, date_from, address, lat, lng, sex, gift_id, new PnwOkCallbackAdapter<HttpRespOrder>() {
            @Override
            public void onResponse(HttpRespOrder response, boolean fresh) {
                super.onResponse(response, fresh);
                dlgLoading.dismiss();
                if (response.errcode == C.http.RESULT_SUCCESS) {

                    Intent intent = new Intent(DateStartActivity.this, DateChooseActivity.class);
                    intent.putExtra(DateChooseActivity.EXTRA_ORDER_ID, response.order.id);
                    startActivity(intent);
                    finish();
                } else if (fresh && response.errcode != C.http.RESULT_LOGIN_EXPIRE &&
                        response.errcode != C.http.RESULT_LOGIN_OFFLINE) {
                    BaseUtil.showToast(response.errmsg);
                }
            }

            @Override
            public void onFailure(Request request, Exception e) {
                super.onFailure(request, e);
                dlgLoading.dismiss();
            }
        });
    }

    private void requestOrderCreateSingle(final String subject_type,final String date_from,final String address, double lat, double lng, int sex, long gift_id) {
        final LoadingDialog dlgLoading = new LoadingDialog.Builder(this).create();
        dlgLoading.show();
        PnwHttpManager.Order.createSingle(TAG, simpleOtherEaseId, subject_type, date_from, address, lat, lng, sex, gift_id, new PnwOkCallbackAdapter<HttpRespOrder>() {
            @Override
            public void onResponse(HttpRespOrder response, boolean fresh) {
                super.onResponse(response, fresh);
                dlgLoading.dismiss();
                if (response.errcode == C.http.RESULT_SUCCESS) {
                    Intent intent = getIntent();
                    intent.putExtra(EXTRA_SIMPLE_ORDER_ID, response.order.id);
                    intent.putExtra(EXTRA_SIMPLE_ORDER_SUBJECT, subject_type);
                    intent.putExtra(EXTRA_SIMPLE_ORDER_TIME, date_from);
                    intent.putExtra(EXTRA_SIMPLE_ORDER_ADDRESS, address);
                    setResult(RESULT_OK, intent);
                    finish();
                } else if (fresh && response.errcode != C.http.RESULT_LOGIN_EXPIRE &&
                        response.errcode != C.http.RESULT_LOGIN_OFFLINE) {
                    BaseUtil.showToast(response.errmsg);
                }
            }

            @Override
            public void onFailure(Request request, Exception e) {
                super.onFailure(request, e);
                dlgLoading.dismiss();
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE_ADDRESS:
                    String address = data.getStringExtra(PoiKeywordSearchActivity.EXTRA_POI);
                    double lat = data.getDoubleExtra(PoiKeywordSearchActivity.EXTRA_LAT, 0);
                    double lng = data.getDoubleExtra(PoiKeywordSearchActivity.EXTRA_LNG, 0);
                    txAddress.setText(address);
                    txAddress.setTag(lat + "#" + lng);
                    break;
            }
        }
    }


}
